handytab.onFirefoxLoad = function(e) {
  var prefSrv = Components.classes["@mozilla.org/preferences-service;1"]
                          .getService(Components.interfaces.nsIPrefService);
  var prefs = prefSrv.getBranch("extensions.handytab.");

  var firstRun = prefs.getBoolPref("firstrun");
  if (firstRun) {
    handytab.addButtonsToToolbar();
    prefs.setBoolPref("firstrun", false);
    prefSrv.savePrefFile(null);
  }
  
  document.getElementById("contentAreaContextMenu")
          .addEventListener("popupshowing", function (e){ handytab.showFirefoxContextMenu(e); }, false);
};

handytab.addButtonsToToolbar = function() {
  try {
    var toolbar = document.getElementById("nav-bar");
    var curSet = toolbar.currentSet;
    var newSet = curSet;
    var buttons = ['show-handytab-button'];

    for (var i = 0; i < buttons.length; i++) {
      if (curSet.indexOf(buttons[i]) == -1) {
        // Place the button after the home-button
        if (newSet.indexOf("home-button") != -1)
          newSet = newSet.replace(/home-button/, "home-button," + buttons[i]);
        else if (newSet.indexOf("stop-button") != -1)  // else place the button after the stop-button
          newSet = newSet.replace(/stop-button/, "stop-button," + buttons[i]);
        else  // else at the end
          newSet += "," + buttons[i];
      }
    }

    if (newSet != curSet) {
      toolbar.setAttribute("currentset", newSet);
      toolbar.currentSet = newSet;
      document.persist("nav-bar", "currentset");
      // If you don't do the following call, funny things happen
      try {
        BrowserToolboxCustomizeDone(true);
      }
      catch (e) { }
    }
  }
  catch(e) { }
};  

handytab.showFirefoxContextMenu = function(e) {
  if (e.originalTarget != document.getElementById("contentAreaContextMenu")) return;
  if (!gContextMenu) return;

  var hideSelf = !gContextMenu.onLink && !gContextMenu.onImage;
  document.getElementById("context-handytab-marklink").hidden = hideSelf;
  document.getElementById("context-handytab-markpage").hidden = !hideSelf;
};

window.addEventListener("load", handytab.onFirefoxLoad, false);
